package com.hulman.oms.service;

import com.hulman.oms.bean.Device;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Accessory;
import com.hulman.oms.dao.AccessoryDao;
import com.hulman.oms.dao.DeviceDao;
import com.hulman.oms.exception.IoTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class AccessoryService
{
    @Autowired
    private AccessoryDao accessoryDao;
    @Autowired
    private DeviceDao deviceDao;

    public List<Accessory> findAccessories(Map<String, Object> map)
    {
        return accessoryDao.findAccessories(map);
    }

    public Integer findAccessoriesCount(Map<String, Object> map)
    {
        return accessoryDao.findAccessoriesCount(map);
    }

    public Result findAccessoriesResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = accessoryDao.findAccessoriesCount(map);
        List<Accessory> data = accessoryDao.findAccessories(map);
        return new Result(data, count);
    }

    public Accessory findAccessoryById(Integer id)
    {
        return accessoryDao.findAccessoryById(id);
    }

    public void saveAccessory(Accessory accessory)
    {
        if (accessory.getId() != null && accessory.getId() != 0)
        {
            accessoryDao.updateAccessory(accessory);
        } else
        {
            accessoryDao.insertAccessory(accessory);
        }
    }

    public void deleteAccessoryById(Integer id)
    {
        accessoryDao.deleteAccessoryById(id);
    }

    public void deleteAccessories(int[] ids)
    {
        accessoryDao.deleteAccessories(ids);
    }

    public void clearAccessoriesByDeviceId(Integer deviceId)
    {
        accessoryDao.clearAccessoriesByDeviceId(deviceId);
    }

    public void importAccessory(Accessory accessory)
    {
        Device device = deviceDao.findDeviceByCode(accessory.getDeviceCode());
        if (device == null)
        {
            throw new IoTException("导入附件失败，找不到设备编号：" + accessory.getDeviceCode());
        }
        Accessory access = accessoryDao.findAccessoryByDeviceIdAndName(device.getId(), accessory.getName());
        if (access != null)
        {
            accessory.setId(access.getId());
        }
        accessory.setDeviceId(device.getId());
        saveAccessory(accessory);
    }

}
